package com.bizfx.component.presenters
{
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.utils.describeType;
	import flash.utils.getDefinitionByName;
	import flash.utils.getQualifiedClassName;
	
	import com.bizfx.component.views.IView;
	import com.bizfx.errors.NoAlertError;
	import com.bizfx.events.ModuleCommandEvent;
	import com.bizfx.events.ViewCommandEvent;
	import com.bizfx.utils.ObjectUtils;
	import com.bizfx.utils.StringUtils;
	
	import mx.controls.Alert;
	import mx.core.Application;
	import mx.logging.ILogger;
	import mx.logging.Log;
	import mx.rpc.AsyncToken;
	
	public class BasePresenter extends EventDispatcher
	{
		protected var className:String;
		
		protected var logger:ILogger;
		/**
		 * 记录当前的ViewCommand
		 */
		protected var currentViewCommand:ViewCommandEvent = null;
		
		private var _view:IView;
		
		/**
		 * 视图
		 */
		public function get view():IView
		{
			return _view;
		}
		
		public function set view(value:IView):void
		{
			if (this._view == value) {
				return;
			}
			this._view = value;
			this.dispatchEvent(new Event("viewChanged"));
			if (this._view) {
				this._view.addEventListener(ViewCommandEvent.ViewCommand_Raise, viewCommandRaiseHandler);
				this._view.addEventListener(ModuleCommandEvent.ModuleCommand_Handle, moduleCommandHandleHandler);
			}
		}
		
		public function BasePresenter()
		{
			className = getQualifiedClassName(this);
			className = StringUtils.replace(className, ".", "_");
			className = StringUtils.replace(className, ":", "_");
			logger = Log.getLogger(className);
			super();
		}
		
		protected function viewCommandRaiseHandler(event:ViewCommandEvent):void {
			this.currentViewCommand = event;
			try {
				if (event.viewCommand) {
					var sender:IView = event.target as IView;
					var methodName:String = this.getViewCommandHandlerMethodName(sender.viewKey, event.viewCommand.commandKey);
					if (!StringUtils.isNullOrEmpty(methodName) && this.hasOwnProperty(methodName)) {
						logger.debug("处理视图事件，调用" + methodName + "方法处理。");
						callEventMethod(methodName, event);
					} else {
						if (event.viewCommand.requestedHandler) {
							var errorMsg:String = "控制器" + className + "没有处理视图事件“" + event.type + "”的方法【" + methodName + "】。" 
							throw new Error(errorMsg);	
						}
					}	
				} else {
					logger.error("ViewCommand为空。");
					Alert.show("ViewCommand为空。", "错 误");
				}
			} catch (e:NoAlertError) {
			} catch (e:Error) {
				logger.error(errorMsg);
				Alert.show(e.message, "错 误");
			}
		}
		
		protected function getViewCommandHandlerMethodName(viewKey:String, commandKey:String):String {
			//通过方法里面的“ViewCommandHandler”来调用处理方法。
			var methodName:String = "";
			var xmlList:XMLList = describeType(this).method.metadata.(@name == "ViewCommandHandler").arg.(@key == "commandKey" && @value == commandKey);
			if (xmlList.length() > 0) {
				var xl:XMLList = xmlList[0].parent().arg.(@key == "view")
				if (xl.length() > 0) {
					if (xl[0].@value == ((viewKey == null)?"":viewKey)) {
						methodName = xmlList[0].parent().parent().@name;
					}
				} else {
					methodName = xmlList[0].parent().parent().@name;
				}
			}
			return methodName;
		}
		
		private function moduleCommandHandleHandler(event:ModuleCommandEvent):void {
			try {
				var sender:IView = event.target as IView;
				
				var methodName:String = "";
				var xmlList:XMLList = describeType(this).method.metadata.(@name == "ModuleCommandHandler").arg.(@key == "commandKey" && @value == event.viewCommand.commandKey);
				if (xmlList.length() > 0) {
					var xl:XMLList = xmlList[0].parent().arg.(@key == "view")
					if (xl.length() > 0) {
						if (xl[0].@value == ((sender.viewKey == null)?"":sender.viewKey)) {
							methodName = xmlList[0].parent().parent().@name;
						}
					} else {
						methodName = xmlList[0].parent().parent().@name;
					}
				}
				
				//				if (!StringUtils.isNullOrEmpty(methodName) && this.hasOwnProperty(methodName)) {
				//					logger.debug("处理视图事件，调用" + methodName + "方法处理。");
				//					var eventMethod:Function = this[methodName];
				//					if (eventMethod != null) {
				//						callEventMethod(eventMethod, event);
				//					}
				//					this.afterViewCommandEventHandler(event);
				//				} else {
				//					if (event.viewCommand.requestedHandler) {
				//						var errorMsg:String = "控制器" + className + "没有处理视图事件“" + event.type + "”的方法【" + methodName + "】。" 
				//						logger.warn(errorMsg);
				//						Alert.show(errorMsg, "错 误");	
				//					}
				//				}
			} catch (e:NoAlertError) {
			} catch (e:Error) {
				Alert.show(e.message, "错 误");
			}
		}
		
		protected function callEventMethod(functionName:String, event:ViewCommandEvent):void {
			var f:Function = this[functionName];
			
			if (event.viewCommand.needConfirm) {
				var confirmHandler: Function = function(dlgObj: Object):void{ 
					if(dlgObj.detail == Alert.OK || dlgObj.detail == Alert.YES){
						f.call(this, event);
					}
				};
				
				var msg:String = "确认" + StringUtils.replace(event.viewCommand.commandName, " ", "") + "所选记录吗?";
				if (!StringUtils.isNullOrEmpty(event.viewCommand.confirmMessage)) {
					msg = event.viewCommand.confirmMessage;
				}
				var confirmDlg: Object = Alert.show(msg, "提 示", Alert.OK|Alert.CANCEL, null, confirmHandler, null, Alert.CANCEL);			
			} else {
				f.call(this, event);
			}
		}
	}
}